//
//  HOTMineDetailListViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-15.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTOrenoSubListViewController.h"
#import "HOTOrenoListCell.h"
#import "HOTImagePriviewer.h"
#import "HOTCreateArticleViewController.h"
#import "HOTOrenoDetailViewController.h"
#import "HOTOrenoListViewController.h"

#define tab_1_cell_id @"tableView_1"

@interface HOTOrenoSubListViewController () <HOTOrenoListCellDelegate>{
    
    NSMutableDictionary *_cellCache;
    //    NSMutableArray *_dataList1;
    //    NSMutableArray *_dataList2;
    //    NSMutableArray *_dataList3;
    
    NSInteger _pageNo;
}
@property(nonatomic,strong)NSMutableArray *dataList;
@property(nonatomic,copy)NSString *category_id;
@property(nonatomic,copy)NSString *reqType;
@end

@implementation HOTOrenoSubListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil category_id:(NSString *)category_id reqType:(NSString *)reqType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.category_id = category_id;
        self.reqType = reqType;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_oreno"]];
    [self setNaviTitle:@"俺のシリーズ"];
    
    [self addRightBtnTarget:self action:@selector(createNewNoteBtnClicked:) image:[UIImage imageNamed:@"btn_note_off"] hImage:[UIImage imageNamed:@"btn_note_on"]];
    
    _cellCache = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    _tableView.showHeader = YES;
    _tableView.showFooter = YES;
    
    __unsafe_unretained HOTOrenoSubListViewController *tempObj = self;
    
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };
    
    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [tempObj requestDataFromNet];
    };
    
    self.dataList = [NSMutableArray array];
    
    _pageNo = 1;
    [self requestDataFromNet];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_CATE_ID:[HOTUtils getString:self.category_id],
                                 REQ_KEY_TYPE:self.reqType,
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};
    
    __unsafe_unretained HOTOrenoSubListViewController *tempObj = self;
    [self requestWithURL:HOT_URL_USER_CONTENT Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_tableView reloadData];
                [self alertNoDataMessage:^{
                    //[tempObj.navigationController popViewControllerAnimated:YES];
                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }
        
        if (_pageNo == 1) {
            [tempObj.dataList removeAllObjects];
        }
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = tab_1_cell_id;
    HOTOrenoListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        cell = [_cellCache objectForKey:@(indexPath.row)];
        
        if (cell == nil) {
            
            cell = [self createTableCellWithCellId:cellId];
        }
    }
    
    cell.delegate = self;
    cell.indexPath = indexPath;
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    
    [self setCell:cell dic:dic];
    cell.majiLabel.user_id = [dic objectForKey:@"user_id"];
    cell.majiLabel.targetVcClass = [HOTOrenoListViewController class];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HOTOrenoListCell *cell = [tableView dequeueReusableCellWithIdentifier:tab_1_cell_id];
    
    if (cell == nil) {
        
        cell = [self createTableCellWithCellId:tab_1_cell_id];
        
        [_cellCache setObject:cell forKey:@(indexPath.row)];
    }
    
    
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row];
    
    [self setCell:cell dic:dic];
    
    [cell setNeedsDisplay];
    [cell setNeedsUpdateConstraints];
    [cell.contentView setNeedsDisplay];
    [cell.contentView setNeedsUpdateConstraints];
    
    float cellH = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
//    NSLog(@"cellH = %f",cellH);
    return cellH +1;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *articleInfo = [self.dataList objectAtIndex:indexPath.row];
    HOTOrenoDetailViewController *odvc = [[HOTOrenoDetailViewController alloc] initWithNibName:@"HOTOrenoDetailViewController" bundle:nil article_id:[HOTUtils getString:[articleInfo objectForKey:@"article_id"]] articleInfo:articleInfo];
    
    [self.parentNavc pushViewController:odvc animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)createNewNoteBtnClicked:(id)sender {
    
    HOTCreateArticleViewController *cavc = [[HOTCreateArticleViewController alloc] initWithNibName:@"HOTCreateArticleViewController" bundle:nil category_id:self.category_id];
    
    [self.navigationController pushViewController:cavc animated:YES];
}

-(void)setCell:(HOTOrenoListCell *)cell dic:(NSDictionary *)dic {
    
    cell.majiLabel.text = [NSString stringWithFormat:@"%@:",[dic objectForKey:@"user_name"]];
    cell.placeName.text = [NSString stringWithFormat:@"【%@】%@", [dic objectForKey:@"city"],[dic objectForKey:@"job_name"]];
    cell.titleLabel.text = [dic objectForKey:@"title"];
    cell.dateTimeLabel.text = [dic objectForKey:@"article_time"];
    cell.contentLabel.text = [dic objectForKey:@"article_content"];
    //NSURL *url = [NSURL URLWithString:[dic objectForKey:@"pic_thumb_url"]];
    if (![HOTUtils isNullOrEmpty:[dic objectForKey:@"pic_thumb_url"]]) {
        
        NSURL *url = [NSURL URLWithString:[dic objectForKey:@"pic_thumb_url"]];
        [cell setContentImage:url];
    } else {
        
        [cell setContentImage:nil];
    }
}

-(HOTOrenoListCell *)createTableCellWithCellId:(NSString *)cellId {
    
    UINib *nib = [UINib nibWithNibName:XIB(@"HOTOrenoListCell") bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:cellId];
    
    HOTOrenoListCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellId];
    
    return cell;
}

-(void)contentImageClicked:(NSIndexPath *)clickIndexPath {
    
    NSDictionary *dic = [self.dataList objectAtIndex:clickIndexPath.row];
    
    NSString *urlStr = [dic objectForKey:@"pic_url"];
    
    if ([HOTUtils isNotNullOrEmpty:urlStr]) {
        
        [[HOTImagePriviewer priviewer] showInView:[[UIApplication sharedApplication] keyWindow] withUrl:urlStr placeHolder:kImageHolder];
    } else {
        
    }
}

@end
